class Solution {
    public List<List<Integer>> permute(int[] nums) {
        int n = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }

        boolean[] used = new boolean[n];
        Deque<Integer> path = new ArrayDeque<>();

        dfs(nums, n, 0, path, used, res);
        return res;
    }

    
    /**深度优先遍历
     *
     * @param nums  数组
     * @param n     数组长度
     * @param depth 当前深度
     * @param path  路径
     * @param used  使用过的元素
     * @param res   存储结果的列表
     */
    private void dfs(int[] nums, int n, int depth, Deque<Integer> path, boolean[] used, List<List<Integer>> res) {
        if (depth == n) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < n; i++) {
            if (!used[i]) {
                path.addLast(nums[i]);
                used[i] = true;

                dfs(nums, n, depth+1, path, used, res);

                used[i] = false;
                path.removeLast();
            }
        }
    }
}